<template>
<el-row class="Register">
    <el-col :span="8" :offset="8">
        <h1 class="title">信息员注册</h1>
    </el-col>
    <el-col :span="8" :offset="8">
        <el-card shadow="never">
            <el-page-header @back="goBack" content="用户注册"> </el-page-header>
            <el-form :model="user" :rules="rules" ref="user" label-width="100px">
                <el-form-item label="真实姓名" prop="trueName">
                    <el-input type="text" v-model="user.trueName" minlength="2" maxlength="30" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="身份证号码" prop="cardID">
                    <el-input type="text" v-model="user.cardID" minlength="15" maxlength="18" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="设置密码" prop="password">
                    <el-input type="password" v-model="user.password" minlength="6" maxlength="18" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input type="password" v-model="user.confirmPassword" minlength="6" maxlength="18" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input type="text" v-model="user.phone" minlength="11" maxlength="11" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="authCode">
                    <el-col :span="11">
                        <el-input type="text" v-model="user.authCode"></el-input>
                    </el-col>
                    <el-col :span="11" :offset="1">
                        <el-button type="primary" @click="sendAuthCode">获取验证码</el-button>
                    </el-col>
                </el-form-item>

                <el-row>
                    <el-col :span="24">
                        <el-alert title="提示：" style="margin-bottom:15px" type="warning" effect="dark">
                            若您是镇街管理人员，请仅填写【选择镇街】即可，
                            请勿填写【选择村居】；若您为村干部等村信息人员，请填写【选择村居】。
                        </el-alert>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="选择镇街" prop="subjectTownId">
                            <el-select v-model="user.subjectTownId" clearable @change="changeOptions">
                                <el-option v-for="(item, index) in options" :key="item.value" :label="item.label" :value="item.value" @click.native="getIndex(index)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12" v-if="user.subjectTownId">
                        <el-form-item label="选择村居">
                            <el-select v-model="user.subjectVillageId" clearable>
                                <el-option v-for="item in options[townIndex].children" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="申请理由" prop="desc">
                    <el-input type="textarea" v-model="user.desc" minlength="15" maxlength="500" show-word-limit></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('user')">立即创建</el-button>
                    <el-button @click="resetForm('user')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </el-col>
</el-row>
</template>

<script>
import {
    regexp
} from "@/library/regexp.js";
import {
    mapGetters
} from "vuex";
export default {
    name: "Register",
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入密码"));
            } else {
                if (this.user.confirmPassword !== "") {
                    this.$refs.user.validateField("confirmPassword");
                }
                callback();
            }
        };

        var validatePass2 = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.user.password) {
                callback(new Error("两次输入密码不一致!"));
            } else {
                callback();
            }
        };

        return {
            value: [],
            townIndex: 0,
            user: {
                trueName: "",
                region: "",
                date1: "",
                date2: "",
                delivery: false,
                type: [],
                userAdministrativeCode: "",
                subjectTownId: "", //所属镇 (区域编码) 必填
                subjectVillageId: "", //所属村 (区域编码)
                desc: "",
            },
            authCode: {
                hash: "",
                tamp: "",
                validateNum: ""
            },
            rules: {
                trueName: [{
                        required: true,
                        message: "请输入您的真实姓名",
                        trigger: "blur"
                    },
                    {
                        min: 2,
                        max: 15,
                        message: "长度在 2 到 15 个字符",
                        trigger: "blur"
                    },
                ],
                cardID: [{
                        required: true,
                        message: "请输入身份证号",
                        trigger: "blur"
                    },
                    {
                        min: 15,
                        max: 18,
                        message: "请如实填写18位身份证号码",
                        trigger: "blur",
                    },
                    {
                        required: true,
                        pattern: regexp.cardID,
                        message: "请输入正确的身份证号码",
                        trigger: "blur",
                    },
                ],
                subjectTownId: [{
                    required: true,
                    message: "镇街必须填写",
                }],

                password: [{
                    required: true,
                    validator: validatePass,
                    trigger: "blur"
                }],
                confirmPassword: [{
                    required: true,
                    validator: validatePass2,
                    trigger: "blur"
                }],
                phone: [{
                        required: true,
                        message: "请输入手机号码",
                        trigger: "blur"
                    },
                    {
                        min: 11,
                        max: 11,
                        message: "请输入11位手机号码",
                        trigger: "blur",
                    },
                    {
                        required: true,
                        pattern: regexp.phone,
                        message: "请输入正确的手机号码",
                        trigger: "blur",
                    },
                ],
                authCode: [{
                    required: true,
                    message: "手机验证码不能为空",
                    trigger: "change"
                }],
                value: [{
                    required: true,
                    message: "必须选择一个行政区域",
                    trigger: "blur"
                }],
                desc: [{
                    required: true,
                    message: "请填写申请说明",
                    trigger: "blur"
                }],
            },
        };
    },
    computed: {
        ...mapGetters({
            options: "getTreeData/filtersVillage",
        }),
    },
    methods: {
        changeOptions() {
            this.user.subjectVillageId = "";
        },
        goBack() {
            console.log("go back");
            history.go(-1);
        },
        submitForm(formName) {

            this.$refs[formName].validate((valid) => {
                if (valid) {

                    if (this.authCode.hash == "" || this.authCode.tamp == "") {
                        this.$message("短信验证码异常，请重新获取")
                        return false;
                    }

                    if (this.user.subjectTownId != "" && this.user.subjectVillageId != "") {
                        this.user.userAdministrativeCode = this.user.subjectVillageId;
                    }

                    if (this.user.subjectTownId != "" && this.user.subjectVillageId == "") {
                        this.user.userAdministrativeCode = this.user.subjectTownId;
                    }

                    if (this.user.subjectTownId == "" && this.user.subjectVillageId != "") {
                        this.$message("请选择正确地级区域")
                        return false;
                    }

                    this.authCode.validateNum = this.user.authCode
                    //TODO: 用户注册
                    this.$common.registerUser(this.user, this.authCode).then((res) => {
                        console.log(res);
                        if (res.code == 0) {
                            this.resetForm('user');
                            this.$router.push({
                                name: "RegisterSuccess"
                            })
                        } else {
                            this.$message({
                                type: "error",
                                duration: 3000,
                                showClose: true,
                                message: res.msg
                            })
                            console.log("error submit!!");
                        }

                    })

                } else {
                    this.$message.error('请填写正确的手机号及注册信息！')
                    console.log("error submit!!");
                    return false;
                }
            });

        },
        getIndex(val) {
            this.townIndex = val;
        },

        //获取验证码
        sendAuthCode() {
            var mobile_mode = /^1[34578]\d{9}$/;
            if (!mobile_mode.test(this.user.phone)) {
                this.$message("手机号格式不正确，请输入正确！");
                return false;
            }
            this.$common.sendAuthCode(this.user.phone, 3).then((res) => {
                if (res.code === 500) {
                    this.$message({
                        type: 'warning',
                        message: `${res.msg}`
                    });
                } else {
                    this.authCode.hash = res.hash;
                    this.authCode.tamp = res.tamp;
                    // this.authCode.validateNum = res.validateNum;
                    this.$message({
                        type: 'info',
                        message: `${res.validateNum}`
                    });
                }

            })
        },

        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    },
};
</script>

<style lang="scss" scoped>
.title {
    margin-top: 54px;
    margin-bottom: 30px;
    font-family: "微软雅黑";
    font-weight: normal;
    font-size: 32px;
    letter-spacing: 0;
    color: #333333;
}

.el-page-header {
    margin: 0 auto 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ddd;
}
</style>
